<template>
  <div style="text-align: left">
    <el-row style="text-align: right;padding: 10px">
      <el-button icon="el-icon-search" size="mini" @click="searchFlagChange" />
      <el-switch
        v-model="deletedStatus"
        inactive-text="回收站开关"
        style="padding: 10px"
        @change="recycleSwitch"
      />
    </el-row>
    <el-form
      v-if="searchFlag"
      ref="searchForm"
      :model="formData"
      :rules="rules"
      size="small"
      label-width="100px"
      label-position="left"
      :inline="true"
      style="padding: 10px"
    >
      <el-form-item label="权限名称" prop="label">
        <el-input
          v-model="formData.label"
          placeholder="请输入权限名称"
          clearable
          style="width: 150px"
          @keyup.enter.native="getPageData"
        />
      </el-form-item>
      <el-form-item label="时间范围" prop="enabled">
        <el-date-picker
          v-model="formData.time"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 350px"
        />
      </el-form-item>
      <el-form-item>
        <BeeButton :loading="loading" code="permissionSearch" type="primary" @click="getPageData('search')">查询</BeeButton>
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="24">
        <div v-if="tableData.length!==0">
          <el-row style="padding-bottom: 10px">
            <el-col :span="24">
              <BeeButton v-show="!deletedStatus" code="permissionAdd" type="success" size="mini" @click="addPermission">新增
              </BeeButton>
              <BeeButton v-show="!deletedStatus" code="permissionBatchDelete" type="danger" size="mini" @click="deleteByIds">
                批量删除
              </BeeButton>
            </el-col>
            <el-col :span="24">
              <BeeButton v-show="deletedStatus" code="permissionClear" type="info" size="mini" @click="clear">
                清空垃圾桶
              </BeeButton>
              <BeeButton v-show="deletedStatus" code="permissionRestore" type="danger" size="mini" @click="recover">恢复
              </BeeButton>
            </el-col>
          </el-row>

          <el-table
            v-loading="loading"
            :size="isMobile()?'mini':'medium'"
            :data="tableData"
            style="width: 100%"
            border
            tooltip-effect="light"
            @selection-change="handleSelectionChange"
            @sort-change="handleSortChange"
          >
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-card>
                  <div slot="header" class="clearfix">
                    <span>详细信息</span>
                  </div>
                  <el-form label-position="left" inline class="table-expand">
                    <el-form-item label="权限名称">
                      <span>{{ props.row.label }}</span>
                    </el-form-item>
                    <el-form-item label="权限码">
                      <span>{{ props.row.code }}</span>
                    </el-form-item>
                    <el-form-item label="创建人">
                      <span>{{ dictTrans(props.row.createUser,'userDict') }}</span>
                    </el-form-item>
                    <el-form-item label="创建时间">
                      <span>{{ props.row.createTime }}</span>
                    </el-form-item>
                    <el-form-item label="更新人">
                      <span>{{ dictTrans(props.row.updateUser,'userDict') }}</span>
                    </el-form-item>
                    <el-form-item label="更新时间">
                      <span>{{ props.row.updateTime }}</span>
                    </el-form-item>
                    <el-form-item label="备注" style="width: 100%">
                      <span>{{ props.row.remark }}</span>
                    </el-form-item>
                  </el-form>
                </el-card>
              </template>
            </el-table-column>
            <el-table-column
              type="selection"
              width="55"
            />
            <el-table-column
              prop="label"
              label="权限名称"
              show-overflow-tooltip
            />
            <el-table-column
              prop="code"
              label="权限码"
              show-overflow-tooltip
            />
            <el-table-column
              prop="createTime"
              label="创建时间"
              sortable
              width="160px"
            />
            <el-table-column
              prop="updateTime"
              label="更新时间"
              sortable
              width="160px"
            />
            <el-table-column
              prop="id"
              label="操作"
              width="150px"
            >
              <template slot-scope="scope">
                <BeeButton
                  :disabled="deletedStatus"
                  code="permissionDelete"
                  size="mini"
                  type="danger"
                  @click="deleteById(scope.row.id)"
                >删除
                </BeeButton>
                <BeeButton
                  :disabled="deletedStatus"
                  code="permissionEdit"
                  size="mini"
                  type="warning"
                  @click="editPermission(scope.row)"
                >编辑
                </BeeButton>
              </template></el-table-column>
          </el-table>
          <el-pagination
            :page-size="size"
            :current-page="current"
            layout="total,sizes, prev, pager, next,jumper"
            :total="total"
            :page-sizes="[ 5, 10, 50, 100]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <el-empty v-else description="查询结果为空" />
      </el-col>
    </el-row>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :width="isMobile()?'100%':'50%'"
      @close="close()"
    >
      <el-row :gutter="15">
        <el-form
          ref="editOrAddForm"
          :model="addOrEditFormData"
          :rules="rulesEditOrAdd"
          size="medium"
          label-width="100px"
          label-position="left"
        >
          <el-col :span="12">
            <el-form-item label="权限名称" prop="label">
              <el-input
                v-model="addOrEditFormData.label"
                placeholder="请输入权限名称"
                clearable
                :style="{width: '100%'}"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限码" prop="code">
              <el-input
                v-model="addOrEditFormData.code"
                placeholder="请输入权限码"
                clearable
                :style="{width: '100%'}"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="addOrEditFormData.remark"

                type="textarea"
                placeholder="请输入备注"
                :maxlength="255"
                show-word-limit
                :autosize="{minRows: 2, maxRows: 4}"
                :style="{width: '100%'}"
              />
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="close()">关闭</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import BeeButton from '@/components/RoleButton/index.vue'
import { formatData, humpToUnderline } from '@/utils/ParamFilter'
import {
  addPermission, clear,
  deleteById, deleteByIds, editPermission,
  page, recover
} from '@/api/permission'
import { MessageBox } from 'element-ui'
import { deepClone, isMobile } from '@/utils/ObjectUtil'
import { dictFilterMixins } from '@/utils/dictFilterMixins'

export default {
  name: 'Permission',
  components: { BeeButton },
  mixins: [dictFilterMixins],
  data() {
    return {
      flagChange: 0,
      isChange: false,
      deletedStatus: false,
      searchFlag: !isMobile(),
      loading: false,
      tableData: [],
      departmentTrees: [],
      current: 0,
      size: 10,
      total: 0,
      orderColumn: '',
      orderAsc: '',
      multipleSelection: [],
      dialogTitle: '',
      showDialog: false,
      buttonLoading: false,
      formData: {
        label: '',
        time: ''
      },
      rules: {
        label: []
      },
      defaultProps: {
        children: 'children',
        label: 'departmentName'
      },
      addOrEditFormData: {
        label: undefined,
        code: undefined,
        remark: undefined
      },
      rulesEditOrAdd: {
        label: [{ required: true, message: '请输入权限名称', trigger: 'blur' },
          { min: 3, max: 15, message: '权限名称长度在 3 到 15 个字符', trigger: 'blur' }],
        code: [{ required: true, message: '请输入权限码', trigger: 'blur' },
          { min: 3, max: 50, message: '权限名称长度在 3 到 50 个字符', trigger: 'blur' }],
        remark: []
      }
    }
  },
  watch: {
    addOrEditFormData: {
      handler() {
        // 弹窗开启的时候检测的表单由空赋了值，有了一次变动，所以是>1而不是大于0
        this.flagChange++
        if (this.flagChange > 1) {
          this.isChange = true
        }
      },
      deep: true
    }
  },
  mounted() {
    this.getDictFilter('userDict')
    this.getPageData()
  },
  methods: {
    isMobile,
    recycleSwitch() {
      this.getPageData()
    },
    searchFlagChange() {
      this.searchFlag = !this.searchFlag
    },
    getPageData(type) {
      this.loading = true
      this.nowDict = undefined
      this.dictInfo = undefined
      if (this.formData.time === null) {
        this.formData.time = ''
      }
      if (type === 'search') {
        this.current = 1
      }
      const data = {
        current: this.current,
        size: this.size,
        label: this.formData.label,
        deleted: this.deletedStatus,
        orderColumn: this.orderColumn,
        orderAsc: this.orderAsc,
        startTime: this.formData.time !== '' ? this.formData.time[0] : '',
        endTime: this.formData.time !== '' ? this.formData.time[1] : ''
      }
      page(data).then(res => {
        this.tableData = formatData(res.data.records)
        this.total = res.data.total
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.loading = false
      })
    },
    addPermission() {
      this.dialogTitle = '新增权限'
      this.showDialog = true
    },
    clear() {
      clear().then(res => {
        if (res.success) {
          this.getPageData()
          this.$message({
            message: '操作成功',
            type: 'success'
          })
        }
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.loading = false
      })
    },
    recover() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请先勾选',
          type: 'info'
        })
        return
      }
      MessageBox({
        title: '提示',
        message: '确认恢复?'
      }).then(() => {
        recover(this.multipleSelection).then(res => {
          if (res.success) {
            this.getPageData()
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          }
        }).catch(err => {
          console.log(err)
        }).finally(() => {
          this.loading = false
        })
      }).catch(() => {
        this.$message({
          message: '取消操作',
          type: 'info'
        })
      })
    },
    deleteById(id) {
      MessageBox({
        title: '提示',
        message: '确定删除?'
      }).then(() => {
        deleteById(id).then(res => {
          if (res.success) {
            this.getPageData()
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          }
        }).catch(err => {
          console.log(err)
        }).finally(() => {
          this.loading = false
        })
      }).catch(() => {
        this.$message({
          message: '取消操作',
          type: 'info'
        })
      })
    },
    deleteByIds() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请先勾选',
          type: 'info'
        })
        return
      }
      MessageBox({
        title: '提示',
        message: '确定删除?'
      }).then(() => {
        deleteByIds(this.multipleSelection).then(res => {
          if (res.success) {
            this.getPageData()
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          }
        }).catch(err => {
          console.log(err)
        }).finally(() => {
          this.loading = false
        })
      }).catch(() => {
        this.$message({
          message: '取消操作',
          type: 'info'
        })
      })
    },
    handleSizeChange(size) {
      this.size = size
      this.getPageData()
    },
    handleCurrentChange(current) {
      this.current = current
      this.getPageData()
    },
    editPermission(data) {
      this.dialogTitle = '编辑权限'
      this.showDialog = true
      this.addOrEditFormData = deepClone(data)
      // 初始化检测数据
      this.isChange = false
      this.flagChange = 0
    },
    handleSelectionChange(selectedData) {
      const selectIds = []
      for (let i = 0; i < selectedData.length; i++) {
        selectIds.push(selectedData[i].id)
      }
      this.multipleSelection = selectIds
    },
    handleSortChange(column) {
      this.orderColumn = humpToUnderline(column.prop)
      if (column.order === 'ascending') {
        this.orderAsc = true
      } else if (column.order === 'descending') {
        this.orderAsc = false
      } else {
        this.orderColumn = ''
        this.orderAsc = ''
      }
      this.getPageData('search')
    },
    close() {
      this.showDialog = false
      this.addOrEditFormData = {
        label: undefined,
        code: undefined,
        remark: undefined
      }
      this.uploadFlag = false
      this.$refs['editOrAddForm'].clearValidate()
    },
    handelConfirm() {
      this.$refs['editOrAddForm'].validate(valid => {
        if (!valid) return
        this.buttonLoading = true
        if (this.dialogTitle === '编辑权限') {
          if (this.isChange) {
            editPermission(this.addOrEditFormData)
              .then(res => {
                if (res.success) {
                  this.getPageData()
                  this.$message({
                    message: '操作成功',
                    type: 'success'
                  })
                }
              }).catch(err => {
                console.log(err)
              }).finally(() => {
                this.close()
                this.buttonLoading = false
              })
          } else {
            this.close()
            this.buttonLoading = false
          }
        } else if (this.dialogTitle === '新增权限') {
          addPermission(this.addOrEditFormData)
            .then(res => {
              if (res.success) {
                this.getPageData()
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
              }
            }).catch(err => {
              console.log(err)
            }).finally(() => {
              this.close()
              this.buttonLoading = false
            })
        }
      })
    }
  }
}
</script>

<style lang="css" scoped>
.table-expand {
  font-size: 0;
}

.table-expand label {
  width: 90px;
  color: #99a9bf;
}

.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
